package notes.java.juc.demo;

/**
 * 普通按例的生产者与消费者
 * 
 * 会出现问题，当生产者与消费者数量不同时，
 * 
 * 生产者多，消费者少就会出现虚假唤醒问题，product出现了大于10了。
 * 生产者少，消费者多就出现了虚假唤醒问题，product出现了负数
 *
 */
public class J8_TestProductorAndCustomer {

	public static void main(String[] args) {
		Clerk clerk = new Clerk();

		new Thread(new Productor(clerk)).start();
//		new Thread(new Productor(clerk)).start();
		new Thread(new Customer(clerk)).start();
		new Thread(new Customer(clerk)).start();
	}

}

// 生产者
class Productor implements Runnable {
	private Clerk clerk;

	public Productor(Clerk clerk) {
		super();
		this.clerk = clerk;
	}

	@Override
	public void run() {
		while (true) {
			try {
				clerk.buy();
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Customer implements Runnable {
	private Clerk clerk;

	public Customer(Clerk clerk) {
		super();
		this.clerk = clerk;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(100);
				clerk.sale();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

/**
 * 店员
 *
 */
class Clerk {
	private int product = 0; // 产品数量

	// 进货
	public synchronized void buy() throws InterruptedException {
		if (product >= 10) {
			
			System.out.println("已经满了...");
			super.wait();
		}
		
		System.out.println("进货..." + product++);
		super.notify();
	}

	// 卖货
	public synchronized void sale() throws InterruptedException {
		if (product <= 0) {
			System.out.println("卖完了...");
			super.wait();
		} 
		
		System.out.println("卖货..." + product--);
		super.notify();
	}
}